<?php
if (!defined('IN_TG')) exit('Access Defined!');
class Mysql
{
    private $host;       //服务器
    private $username;   //用户名
    private $password;   //密码
    private $dbname;     //数据库名
    private $conn;       //数据库连接标识
    private $sql;        //当前的sql

    //构造函数，初始化
    function __construct($host,$username,$password,$dbname)
    {
    	$this->host=$host;
    	$this->username=$username;
    	$this->password=$password;
    	$this->dbname=$dbname;
    	$this->connect();
    }

    //连接数据库
    private function connect()
    {
    	@$this->conn = mysqli_connect($this->host, $this->username, $this->password, $this->dbname);
		if(mysqli_connect_errno())
		{
			$this->DisplayError('连接数据库失败，可能数据库密码不对或数据库服务器出错！',0);
		}
    	mysqli_set_charset($this->conn, 'UTF8');
    }

    //运行Sql语句,不返回结果集  如update,delete,insert等 
    public function query($sql)  
    {
    	$this->sql=$sql;
        if (!$res = mysqli_query($this->conn,$this->sql)) {
        	if (defined('DEBUG')){
        		$this->DisplayError(mysqli_error($this->conn).' <br><strong>Error sql：</strong> '.$sql);
        	}else{
        		$this->DisplayError('SQL执行失败');
        	}
        	
        }
        return $res;
    }

    //运行Sql,以多维数组方式返回结果集 
    public function getData($sql,$key='',$val='')
    {
        $data=array();
    	//执行sql语句 返回mysqli_result对象
    	$res=$this->query($sql);
    	//如果结果集是bool型，说明执行的不是SELECT语句
    	if (is_bool($res)) return $res;
    	//把结果集循环保存在数组里面
        while($array = mysqli_fetch_array($res, MYSQL_ASSOC)){
        	if ($key) {
        		$data[$array[$key]] = $val ? $array[$val] : $array;
        	}else{
        		$data[] = $array;
        	}
        }
        return $data;       
    }

    //运行Sql，返回第一条数据，没有数据则返回false
    public function getOne($sql)
    {
    	if(!preg_match("/LIMIT/i", $sql)) $sql=$sql." LIMIT 1";
    	$data = $this->getData($sql);
        if ($data) {  
            return reset($data);
        } else {  
            return FALSE;  
        }
    }

    //查询数据,获取指定ID记录或者指定条件记录
    public function find($table,$conid=0,$where='',$fileds='*')
    {	
    	$sql = "SELECT {$fileds} FROM {$table} WHERE ";
    	$sql = $where ? $sql."{$where}" : $sql."id={$conid}";
    	$row=$this->getOne($sql);
    	//判断是不是只有一个字段，如果只有一个，则直接返回这个字段的值
    	if ($fileds!='*' && strpos($fileds,',')===false) {
    		return $row[$fileds];
    	}
    	return $row;
    }

    //插入数据
    public function insert($table,$dataArray)
    {
		if( !is_array($dataArray) || count($dataArray)<=0) {
			$this->DisplayError('没有要插入的数据');
		} 
	    $fileds = array();  // 列名 
	    $values = array();  // 值
	    foreach ($dataArray as $key => $value) {  
	        $fileds[] = "`".$key."`";  
	        $values[] = "'".$value."'";  
	    }  
	    $str_fileds = implode(',', $fileds);  
	    $str_values = implode(',', $values);
	    $sql = "INSERT INTO `".$table."` (".$str_fileds.") VALUES (".$str_values.")";
		$this->query($sql);
		return $this->getLastID();
    }

    //删除数据，返回受影响的行数
    public function delete($table,$conid=0,$where='')
    {
    	$sql = "DELETE FROM {$table} WHERE ";
    	$sql = $where ? $sql."{$where}" : $sql."id={$conid}";
    	//执行SQL，并返回受影响的行数
    	$this->query($sql);
    	return $this->affectedRows();
    }

    //更新数据，返回受影响的行数
    public function update($table,$dataArray,$conid=0,$where='')
    {
		if( !is_array($dataArray) || count($dataArray)<=0) {
			$this->DisplayError('没有要修改的数据');
		} 
	    // 更新的值  
	    $arr_params = array();  
	    foreach ($dataArray as $key => $value) {  
	        if(is_null($value)){  
	            $arr_params[] = "`".$key."` = NULL";  
	        }else{  
	            $arr_params[] = "`".$key."` = '".$value."'";  
	        }  
	    }
	    $str_fileds = implode(',', $arr_params);
	    $sql = "UPDATE `{$table}` SET {$str_fileds} WHERE ";
	    // 更新的条件
	    $sql = $where ? $sql."{$where}" : $sql."id={$conid}";
	    //执行SQL，并返回受影响的行数
    	$this->query($sql);
    	return $this->affectedRows();
    }

    //返回符合条件的总行数
    public function getCount($table,$where="")
    {
        $sql="SELECT COUNT(*) AS count FROM {$table}";
        if ($where) $sql.="{$where}";
        $rs=$this->getOne($sql);
        return intval($rs['count']);
    }

    //执行sql返回总条数
    public function getNumRows($sql)
    {
        return mysqli_num_rows($this->query($sql));
    }

    //获取上一步INSERT操作产生的ID
    public function getLastID()
    {
    	return mysqli_insert_id($this->conn);
    }

    //获取受到影响的条数
    public function affectedRows()
    {
    	return mysqli_affected_rows($this->conn);
    }

    //获得当前的页面文件的url
	public function getCurUrl()
	{
		if(!empty($_SERVER['REQUEST_URI']))
		{
			$nowurls = explode('?',$_SERVER['REQUEST_URI']);
			$nowurl = $nowurls[0];
		}
		else
		{
			$nowurl = $_SERVER['PHP_SELF'];
		}

		return $nowurl;
	}

    //显示数据链接错误信息
    function DisplayError($msg,$t=1)
    {
        //向浏览器输出错误
        switch($t)
        {
            case 0:
            $title = '安全警告：MySql Error！';
            break;
            case 1:
            $title = '安全警告：请检查您的SQL语句是否合法，您的操作将被强制停止！';
            break;
            default;
        }
        $str  = '<div style="font-family:\'微软雅黑\';font-size:12px;">';
        $str .= '<h3 style="margin:0;padding:0;line-height:30px;color:red;">'.$title.'</h3>';
        //$str .= '<strong>错误文件</strong>：'.GetCurUrl().'<br />';
        $str .= '<strong>错误信息</strong>：'.$msg.'';
        $str .= '</div>';
        //保存MySql错误日志
        $pageUrl  = $_SERVER['REQUEST_URI'];
        $getTime = date('Y-m-d H:i:s');
        $logfile = dirname(__FILE__).'/mysql_error_log.php';
        $error = mysqli_error($this->conn);
        $savemsg = "Time : {$getTime}\r\nPage : {$pageUrl}\r\nSql : {$this->sql}\r\nError : {$error}\r\n\r\n";
        //把结果写入日志
        file_put_contents($logfile,$savemsg,FILE_APPEND);
        //输出错误提示
        echo $str;
        exit();
    }

}